package org.jeecg.modules.gongqiang.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.bank.service.IYcUserhomeBankService;
import org.jeecg.modules.front.entity.vo.AuthenticationUserhome;
import org.jeecg.modules.front.entity.vo.FrontUserhomeBank;
import org.jeecg.modules.front.util.YinShengUtil;
import org.jeecg.modules.gongqiang.entity.TmpUserhomeInfo;
import org.jeecg.modules.gongqiang.entity.Userhome;
import org.jeecg.modules.gongqiang.service.ITmpUserhomeInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.gongqiang.service.IUserhomeAuthenticationService;
import org.jeecg.modules.gongqiang.service.IUserhomeService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 用户临时表
 * @Author: jeecg-boot
 * @Date:   2024-09-27
 * @Version: V1.0
 */
@Api(tags="用户临时表")
@RestController
@RequestMapping("/gongqiang/tmpUserhomeInfo")
@Slf4j
public class TmpUserhomeInfoController extends JeecgController<TmpUserhomeInfo, ITmpUserhomeInfoService> {
	@Autowired
	private ITmpUserhomeInfoService tmpUserhomeInfoService;

	 @Autowired
	 private IUserhomeService userhomeService;

	 @Autowired
	 private IUserhomeAuthenticationService userhomeAuthenticationService;

	 @Autowired
	 private IYcUserhomeBankService ycUserhomeBankService;


	/**
	 * 分页列表查询
	 *
	 * @param tmpUserhomeInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "用户临时表-分页列表查询")
	@ApiOperation(value="用户临时表-分页列表查询", notes="用户临时表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TmpUserhomeInfo>> queryPageList(TmpUserhomeInfo tmpUserhomeInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TmpUserhomeInfo> queryWrapper = QueryGenerator.initQueryWrapper(tmpUserhomeInfo, req.getParameterMap());
		Page<TmpUserhomeInfo> page = new Page<TmpUserhomeInfo>(pageNo, pageSize);
		IPage<TmpUserhomeInfo> pageList = tmpUserhomeInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param tmpUserhomeInfo
	 * @return
	 */
	@AutoLog(value = "用户临时表-添加")
	@ApiOperation(value="用户临时表-添加", notes="用户临时表-添加")
	//@RequiresPermissions("org.jeecg.modules:tmp_userhome_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TmpUserhomeInfo tmpUserhomeInfo) {
		tmpUserhomeInfoService.save(tmpUserhomeInfo);
		return Result.OK("添加成功！");
	}


	 /**
	  *   添加
	  *
	  * @param tmpUserhomeInfo
	  * @return
	  */
	 @AutoLog(value = "用户临时表-添加")
	 @ApiOperation(value="用户临时表-添加", notes="用户临时表-添加")
	 //@RequiresPermissions("org.jeecg.modules:tmp_userhome_info:add")
	 @PostMapping(value = "/addin")
	 public Result<String> addin(@RequestBody TmpUserhomeInfo tmpUserhomeInfo) {

		 List<TmpUserhomeInfo> userhomeInfoLists=tmpUserhomeInfoService.list();
		 for (TmpUserhomeInfo temp :userhomeInfoLists
				 ) {
			 try {
				 //第一步创建平台账号
				 Userhome userhome=userhomeService.getByUsername(temp.getMail());
				 if(oConvertUtils.isEmpty(userhome))
				 {
					 userhome=new Userhome();
					 userhome.setUsername(temp.getMail());
					 userhome.setPhone(temp.getPhone());
					 userhome.setStatus(1);
					 userhome.setCreateTime(new Date());
					 userhome.setUpdateTime(new Date());
					 Random random = new Random();
					 String password = "?ac" + String.valueOf(random.nextInt(90000000) + 10000000);
					 userhome.setPassword(password);
					 userhome.setSalt(String.valueOf(random.nextInt(90000000) + 10000000));
					 temp.setPassword(password);
					 //产生邀请码
					 LocalDateTime now = LocalDateTime.now();
					 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
					 String inviteCode = now.format(formatter);
					 userhome.setInviteCode(inviteCode);
					 userhomeService.save(userhome);
					 String userpassword = PasswordUtil.encrypt(String.valueOf(userhome.getId()), password, userhome.getSalt());
					 userhome.setPassword(userpassword);
					 userhome.setIsBuy(1);
					 userhomeService.updateById(userhome);
				 }
				 temp.setStatus(1);
				 tmpUserhomeInfoService.updateById(temp);
				 //第二创建个人钱包实名
				 AuthenticationUserhome authenticationUserhome=new AuthenticationUserhome();
				 authenticationUserhome.setPhone(temp.getPhone());
				 authenticationUserhome.setRealName(temp.getName());
				 authenticationUserhome.setCertNo(temp.getCertNo());
				 Result<String> r1=userhomeAuthenticationService.authentication(authenticationUserhome,userhome.getId());
				 if(r1.isSuccess())
				 {
					 temp.setStatus(2);
					 tmpUserhomeInfoService.updateById(temp);
				 }
				 else
				 {
					 temp.setStatus(3);
					 temp.setRemark(r1.getMessage());
					 tmpUserhomeInfoService.updateById(temp);
					 continue;
				 }
				 //第三绑定银行卡
				 FrontUserhomeBank frontUserhomeBank=new FrontUserhomeBank();
				 frontUserhomeBank.setBankName(temp.getBankName());
				 frontUserhomeBank.setPhone(temp.getPhone());
				 frontUserhomeBank.setBankTypeId(temp.getBankTypeId());
				 frontUserhomeBank.setBankNumber(temp.getBankNo());
				 Result<String> r2= ycUserhomeBankService.bind(frontUserhomeBank,userhome.getId());
				 if(r2.isSuccess())
				 {
					 temp.setStatus(5);
					 tmpUserhomeInfoService.updateById(temp);
				 }
				 else
				 {
					 temp.setStatus(6);
					 temp.setRemark(r2.getMessage());
					 tmpUserhomeInfoService.updateById(temp);
					 continue;
				 }

			 }
			 catch (Exception e) {
				 log.error(e.getMessage());

			 }
		 }
		 return Result.OK("添加成功！");
	 }


	 @AutoLog(value = "上下")
	 @ApiOperation(value="上下", notes="上下")
	 //@RequiresPermissions("org.jeecg.modules:tmp_userhome_info:add")
	 @PostMapping(value = "/addup")
	 public Result<String> addup(@RequestBody TmpUserhomeInfo tmpUserhomeInfo) {

		 List<TmpUserhomeInfo> userhomeInfoLists=tmpUserhomeInfoService.list();
		 for (TmpUserhomeInfo temp :userhomeInfoLists
		 ) {
			 try {
				 if(oConvertUtils.isNotEmpty(temp.getInviteMail()))
				 {
					 Userhome invitUserhome=userhomeService.getByUsername(temp.getInviteMail());
					 if(oConvertUtils.isNotEmpty(invitUserhome))
					 {

						 Userhome selfUserhome=userhomeService.getByUsername(temp.getMail());
						 if(oConvertUtils.isNotEmpty(selfUserhome)&&oConvertUtils.isEmpty(selfUserhome.getInviterId())&&!selfUserhome.getId().equals(invitUserhome.getId()))
						 {
							 invitUserhome.setInviteNum(invitUserhome.getInviteNum()+1);
							 userhomeService.updateById(invitUserhome);
							 selfUserhome.setInviterId(invitUserhome.getId());
							 selfUserhome.setInviterUsername(invitUserhome.getUsername());
							 selfUserhome.setInviterPhone(invitUserhome.getPhone());
							 userhomeService.updateById(selfUserhome);
						 }
					 }
				 }
			 }
			 catch (Exception e) {
				 log.error(e.getMessage());

			 }
		 }
		 return Result.OK("添加成功！");
	 }



	 /**
	  *   添加
	  *
	  * @param tmpUserhomeInfo
	  * @return
	  */
	 @AutoLog(value = "查询")
	 @ApiOperation(value="查询", notes="查询")
	 //@RequiresPermissions("org.jeecg.modules:tmp_userhome_info:add")
	 @PostMapping(value = "/search")
	 public Result<String> search(@RequestBody TmpUserhomeInfo tmpUserhomeInfo) {
		 YinShengUtil.UserInfoByCertNo("422302196510200712");
		 return Result.OK("添加成功！");
	 }


	/**
	 *  编辑
	 *
	 * @param tmpUserhomeInfo
	 * @return
	 */
	@AutoLog(value = "用户临时表-编辑")
	@ApiOperation(value="用户临时表-编辑", notes="用户临时表-编辑")
	//@RequiresPermissions("org.jeecg.modules:tmp_userhome_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TmpUserhomeInfo tmpUserhomeInfo) {
		tmpUserhomeInfoService.updateById(tmpUserhomeInfo);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "用户临时表-通过id删除")
	@ApiOperation(value="用户临时表-通过id删除", notes="用户临时表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:tmp_userhome_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		tmpUserhomeInfoService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "用户临时表-批量删除")
	@ApiOperation(value="用户临时表-批量删除", notes="用户临时表-批量删除")
	//@RequiresPermissions("org.jeecg.modules:tmp_userhome_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tmpUserhomeInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "用户临时表-通过id查询")
	@ApiOperation(value="用户临时表-通过id查询", notes="用户临时表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TmpUserhomeInfo> queryById(@RequestParam(name="id",required=true) String id) {
		TmpUserhomeInfo tmpUserhomeInfo = tmpUserhomeInfoService.getById(id);
		if(tmpUserhomeInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tmpUserhomeInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tmpUserhomeInfo
    */
    //@RequiresPermissions("org.jeecg.modules:tmp_userhome_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TmpUserhomeInfo tmpUserhomeInfo) {
        return super.exportXls(request, tmpUserhomeInfo, TmpUserhomeInfo.class, "用户临时表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("tmp_userhome_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TmpUserhomeInfo.class);
    }

}
